package br.unesp.demac.ccn07.clientes.apresentacao;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import java.sql.SQLException;

import javax.swing.*;

import br.unesp.demac.ccn07.clientes.dao.ClientDAO;
import br.unesp.demac.ccn07.clientes.vo.Clientes;

public class ClienteForm extends JFrame implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField tfId;
	private JTextField tfNome;
	private JTextField tfEmail;
	private JTextField tfTelefone;
	private JButton btSalvar;
	private JButton btCancelar;
	private ClienteTable ct;

	public ClienteForm(ClienteTable ct){
		this.ct = ct;
		setTitle("Cadastro de Clientes");
		Container cp = getContentPane();
		cp.setLayout(new GridLayout(5 ,2, 5, 5));
		cp.add(new JLabel("Codigo", JLabel.LEFT));
		cp.add(tfId = new JTextField());
		cp.add(new JLabel("Nome", JLabel.LEFT));
		cp.add(tfNome = new JTextField());
		cp.add(new JLabel("E-mail", JLabel.LEFT));
		cp.add(tfEmail = new JTextField());
		cp.add(new JLabel("Telfone", JLabel.LEFT));
		cp.add(tfTelefone = new JTextField());
		cp.add(btSalvar = new JButton("Salvar"));
		cp.add(btCancelar = new JButton("Cancelar"));
		btSalvar.addActionListener(this);
		btCancelar.addActionListener(this);
		setSize(400, 200);
	}
	
	

	@Override
	public void actionPerformed(ActionEvent event) {
		if (event.getSource() == btSalvar) {
			try {
				ClientDAO dao = new ClientDAO();
				Clientes cli = new Clientes();
				cli.setId(Integer.parseInt(tfId.getText()));
				cli.setNome(tfNome.getText());
				cli.setEmail(tfEmail.getText());
				cli.setTelefone(tfTelefone.getText());
				dao.insertClient(cli);
				
				dao.getConexao().close();
				setVisible(false);
				ct.refreshTable();
					
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


		}
		else if (event.getSource() == btCancelar) {
			setVisible(false);
		}
		

	}

}
